#include "imageuploadmanager.h"


ImageUploadManager::ImageUploadManager(QObject *parent)
    : QObject(parent)
    , m_uploader(new QiniuUploader(this))
    , m_uploadHistoryModel(new QStandardItemModel(this))
{
    // 设置上传历史模型的列标题
    QStringList headers;
    headers << "文件名" << "URL" << "大小" << "上传时间";
    m_uploadHistoryModel->setHorizontalHeaderLabels(headers);

    // 连接信号与槽
    connect(m_uploader, &QiniuUploader::uploadProgress, this, &ImageUploadManager::handleUploadProgress);
    connect(m_uploader, &QiniuUploader::uploadSuccess, this, &ImageUploadManager::handleUploadSuccess);
    connect(m_uploader, &QiniuUploader::uploadFailed, this, &ImageUploadManager::handleUploadFailed);
}

ImageUploadManager::~ImageUploadManager()
{
}

void ImageUploadManager::initialize(const QString &accessKey, const QString &secretKey,
                                   const QString &bucket, const QString &region)
{
    m_uploader->setConfig(accessKey, secretKey, bucket, region);
}

void ImageUploadManager::startUpload()
{
    // 打开文件选择对话框，选择图片
    m_currentFilePath = QFileDialog::getOpenFileName(nullptr,
        "选择图片","C:/Users/admin/Pictures/Saved Pictures",
        "图片文件 (*.png *.jpg *.jpeg *.bmp *.gif)");

    qDebug()<<m_currentFilePath;

    if (m_currentFilePath.isEmpty()) {
        return; // 用户取消选择
    }

    // 启动上传
    m_uploader->uploadFile(m_currentFilePath);
}

QStandardItemModel* ImageUploadManager::getUploadHistoryModel() const
{
    return m_uploadHistoryModel;
}

void ImageUploadManager::handleUploadProgress(int percent)
{
    emit uploadProgress(percent);
}

void ImageUploadManager::handleUploadSuccess(const QString &fileUrl, const QString &key)
{

    QFileInfo fileInfo(m_currentFilePath);
    QString uploadTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");

    // 添加上传记录
    addUploadRecord(fileInfo.fileName(), fileUrl, fileInfo.size(), uploadTime);

    emit uploadFinished(true, "图片上传成功: " + fileUrl);
}

void ImageUploadManager::handleUploadFailed(const QString &errorMsg)
{
    emit uploadFinished(false, "图片上传失败: " + errorMsg);
}


void ImageUploadManager::addUploadRecord(const QString &filename, const QString &fileUrl,
                                         qint64 size, const QString &uploadTime)
{
    QList<QStandardItem*> rowItems;

    // 文件名
    rowItems.append(new QStandardItem(filename));

    // URL
    rowItems.append(new QStandardItem(fileUrl));

    // 文件大小（格式化为KB或MB）
    QString sizeStr;
    if (size < 1024) {
        sizeStr = QString::number(size) + " B";
    } else if (size < 1024 * 1024) {
        sizeStr = QString::number(size / 1024.0, 'f', 2) + " KB";
    } else {
        sizeStr = QString::number(size / (1024.0 * 1024.0), 'f', 2) + " MB";
    }
    rowItems.append(new QStandardItem(sizeStr));

    // 上传时间
    rowItems.append(new QStandardItem(uploadTime));

    m_uploadHistoryModel->appendRow(rowItems);
}
